package com.qjs.activity.rookie.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qjs.activity.rookie.exception.MyException;
import com.qjs.dto.Response;
import com.qjs.weixin.customer.dto.UserInfo;
import com.qjs.weixin.customer.model.User;
import com.qjs.weixin.customer.service.IUserService;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/user")
public class UserTestController {
	private Logger log = Logger.getLogger(UserTestController.class);

	@Resource
	private IUserService<User> userService;

	@RequestMapping(value = "/getUser/{id}", method = RequestMethod.GET)
	@ResponseBody
	public User getUser(@PathVariable String id) throws Exception {
		log.debug("getUser开始");
		User user = userService.getUser(id);
		Integer a = null;
		if (a > 0) {
			System.out.println("dsd");
		}
		return null;
	}

	@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
	@ResponseBody
	public Response saveUser(@Valid UserInfo userInfo, BindingResult result) throws Exception {
		log.debug("saveUser开始");
		Map<String, String> map = new HashMap<String, String>();
		if (result.hasErrors()) {
			List<FieldError> errorList = result.getFieldErrors();
			for (FieldError e : errorList) {
				System.out.println("er_" + e.getField() + ":" + e.getDefaultMessage());
				map.put("er_" + e.getField(), e.getDefaultMessage());
			}
			JSONObject jsonObject = JSONObject.fromObject(map);
			System.out.println(jsonObject.toString());

			return new Response(-1, map, "参数校验失败");
		}
		return new Response(1, null, "保存成功");
	}

	@RequestMapping(value = "/editUser/id/{id}", method = RequestMethod.GET)
	public String editUser(@PathVariable String id) {
		log.debug("editUser开始");
		Integer a = null;
		if (a > 1) {
			throw new MyException("1", "失败");
		}
		return "index";

	}

}
